import cgi
import tenjin
import rtorrent
import time
import sys
import cgitb; cgitb.enable()
import ConfigParser
import os


############# Form parsing  #################################

config = ConfigParser.ConfigParser()
rt = rtorrent.rtorrent()
message = ''

config = ConfigParser.ConfigParser()
config.readfp(open('config.cfg'))
torrents_dir = config.get('config', 'torrents_dir')

config.set('config', 'torrents_dir', 'fsdfas')



def download(url):
	"""Copy the contents of a file from a given URL
	to a local file.
	"""
	import urllib
	webFile = urllib.urlopen(url)
	localFile = open(torrents_dir + '/' + url.split('/')[-1] + '.torrent', 'w')
	localFile.write(webFile.read())
	webFile.close()
	localFile.close()



try: # Windows needs stdio set for binary mode.
    import msvcrt
    msvcrt.setmode (0, os.O_BINARY) # stdin  = 0
    msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
    pass

form = cgi.FieldStorage()

if form.getvalue('torrents_dir'):
	config.set('config', 'torrents_dir', form['torrents_dir'].value)
	message = message + 'Options saved:' + form['torrents_dir'].value 


if form.getvalue('delete'):
	keys = form.keys()
	for key in keys:
		if form[key].value == 'on':
			if rt.delete_download(key) == 0:
				message = message + ' Torrent deleted successfuly <br>'

if form.getvalue('pause'):
	keys = form.keys()
	for key in keys:
		if form[key].value == 'on':
			if rt.pause_download(key) == 0:
				message = message + ' Torrent paused successfuly <br>'


if form.getvalue('resume'):
	keys = form.keys()
	for key in keys:
		if form[key].value == 'on':
			if rt.resume_download(key) == 0:
				message = message + ' Torrent resumed successfuly <br>'

url = form.getvalue('url')
if url:
	download(url)
	message = 'File downloaded'


# A nested FieldStorage instance holds the file
if form.getvalue('file'):
	fileitem = form['file']

	# Test if the file was uploaded
	if fileitem.filename:
	   
	   # strip leading path from file name to avoid directory traversal attacks
	   fn = os.path.basename(fileitem.filename)
	   open(torrents_dir + '/' + fn, 'wb').write(fileitem.file.read())
	   message = 'The file "' + fn + '" was uploaded successfully'





############## Web generation #############################################3


rt = rtorrent.rtorrent()
active_list = rt.get_list()
inactive_list = rt.get_done_list()

down_rate = 0.00
for download in active_list:
	down_rate = down_rate + float(download[3])


up_rate = 0.00
for download in inactive_list:
	up_rate += float(download[2])


from tenjin.helpers import *   # or escape, to_str
engine = tenjin.Engine()

context = { 'title': 'rtorrent WEBUI (' + str(down_rate) + ' / ' + str(up_rate) + ')', 
	    'active_list': active_list,
	    'inactive_list': inactive_list,
	    'torrents_dir': torrents_dir
	  }

filename = 'main.pyhtml'
output = engine.render(filename, context)
print output,
